/**
 * UserDAO.java
 *
 * $Id$
 *
 */
package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import bean.User;

/**
 * 
 * @author Dyego Souza do Carmo
 * @since 
 */
public class UserDAO extends GenericDAO {

    ResultSet rs = null;
    
    private static final long serialVersionUID = 1L;

    /**
     * Construtor padrão
     *
     * @author Dyego Souza do Carmo
     * @version 1.0, 
     */
    public UserDAO() {
    }

    public boolean isValidUserAndPassword(String user,String password) throws SQLException {
        boolean toReturn = false;
         rs = executeQuery("SELECT * FROM USERS WHERE LOGIN = ? AND PASSWORD = ?",user,password);
        if (rs.next()) {
            toReturn = true;
        }
        rs.close();
        return toReturn;
    }
    
    public int addUser(User usr) throws SQLException {
        usr.setId(getNextId("USERS"));
        String query = "INSERT INTO USERS (ID,NAME,LOGIN,PASSWORD) values (?,?,?,md5('?'))";
        executeCommand(query, usr.getId(), usr.getName(), usr.getLogin(), usr.getPassword());
        return usr.getId();
    }

    public void removeUser(int idUser) throws SQLException {
        executeCommand("DELETE FROM USERS WHERE ID = ?", idUser);
    }

    public void updateUser(User usr) throws SQLException {
        String query = "UPDATE USERS SET NAME=?,LOGIN=?,PASSWORD=? WHERE ID = ?";
        executeCommand(query, usr.getName(), usr.getLogin(), usr.getPassword(), usr.getId());
    }

    public User getUser(int idUser) throws SQLException {
         rs = executeQuery("SELECT * FROM USERS WHERE ID = ?", idUser);
        User usr = null;
        if (rs.next()) {
            usr = populateUserInfo(rs);
        }
        rs.close();
        return usr;
    }

    public List<User> getAllUsers() throws SQLException {
         rs = executeQuery("SELECT * FROM USERS");
        List<User> toReturn = new LinkedList<User>();
        while (rs.next()) {
            toReturn.add(populateUserInfo(rs));
        }
        rs.close();
        return toReturn;
    }

    public static User populateUserInfo(ResultSet rs) throws SQLException {
        User toReturn = new User();
        toReturn.setId(rs.getInt("ID"));
        toReturn.setLogin(rs.getString("LOGIN"));
        toReturn.setName(rs.getString("NAME"));
        toReturn.setPassword(rs.getString("PASSWORD"));
        return toReturn;
    }
}
